#include<iostream>
#include<cstdlib>
#include<unistd.h>
#include<string>
#include"../Util.hpp"

using namespace std;

bool GetQueryString(std::string &query_param)
{
    bool result=false;
    // 标准输入和标准输出在程序替换时就被重定向了
    // cerr<<"method:"<<getenv("METHOD")<<endl;
    std::string method=getenv("METHOD");
    int content_length;
    // 根据方法的不同来处理cgi程序
    if(method=="GET") // 环境变量传递参数
    {
        cerr<<"query_param:"<<getenv("QUERY_PARAM")<<endl;
        query_param=getenv("QUERY_PARAM");
        result=true;
    }
    else if (method=="POST") // 请求正文来传递参数
    {
        cerr<<"content_length:"<<getenv("CONTENT_LENGTH")<<endl;
        content_length=atoi(getenv("CONTENT_LENGTH"));
        char ch=0;
        while(content_length--)
        {
            read(0,&ch,1);
            query_param.push_back(ch);
        }
        result=true;
    }
    else
    {
        result=false;
    }
    return result;
}

int main()
{
    std::string query_param;
    GetQueryString(query_param);
    // a=100&b=200
    std::string str1;
    std::string str2;
    Util::CutString(query_param,str1,str2,"&");

    std::string name1;
    std::string value1;
    Util::CutString(str1,name1,value1,"=");

    std:string name2;
    std::string value2;
    Util::CutString(str2,name2,value2,"=");


    std::cout<<"name1: "<<name1<<" value1: "<<value1<<std::endl;
    std::cout<<"name2: "<<name1<<" value2: "<<value2<<std::endl;

    std::cerr<<"name1: "<<name1<<" value1: "<<value1<<std::endl;
    std::cerr<<"name2: "<<name1<<" value2: "<<value2<<std::endl;

    return 0;
}
